import json
from django.shortcuts import render, redirect
from django.http import JsonResponse,HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from .models import Attachment

from ossfilefield.utils import getTempUrl


def customedTemplateAndView(req):
    return render(req, "page/customed-template-and-view.html", locals())


def nativeJs(req):
    if req.user.is_authenticated:
        attachments = Attachment.objects.filter(owner = req.user)
        message = f"已经登录为{req.user.username}"
    else:
        message = "请先去/admin登录."
    return render(req, "page/native-js.html", locals())


@csrf_exempt
def tempUrl(req):
    '''
    参考 ossfilefield.view.
    :param req:
    :return:
    '''
    data = json.loads(req.body)
    filename = "files/" + data.get("filename")
    # filename = data.get("filename")
    # FIXME 检查filename安全, 或者根据模块写死filename
    resp = getTempUrl(filename, "put_object")

    return HttpResponse(resp)


@csrf_exempt
def registFile(req):
    data = json.loads(req.body)
    filename = data.get("filename")
    if req.user.is_authenticated:
        Attachment.objects.create(
            owner = req.user,
            title = filename,
            file = f"files/{filename}",
        )
        return JsonResponse({"msg":"success"})
    else:
        return JsonResponse({"error":"need login"})


@csrf_exempt
def getFile(req):
    id = req.GET.get("id")
    # 应该保护这个方法, 防止报错.
    attachment = Attachment.objects.get(id=id)
    errors = []
    if not req.user.is_authenticated:
        errors.append("你需要先登录")
    elif req.user != attachment.owner:
        errors.append("你不能访问别人的文件")

    if errors:
        return JsonResponse({"errors": errors})
    else:
        tempDownloadUrl = getTempUrl(attachment.file, "get_object")
        return redirect(tempDownloadUrl)
